import logging
import tkinter as tk
import platform
import CSCommunication
import tkinter.messagebox
from Login import *
import socket
import wmi
import re

##############
#author:张子路#
##############

class DeviceRegistUI():

    def __init__(self):
        self.HostInformation={}
        self.wmiobj = wmi.WMI()
        try:
            self.Communcate=CSCommunication.CSCommunication()
        except Exception as e:
            logging.error("连接文件CSCommunication.py失败 {0}".format(e), exc_info=True)

    def Start(self):
        self.StartDeviceRegistUI()    #生成界面

    def Close(self,CurrentWindow):
        try:
            CurrentWindow.destroy()  #关闭界面
        except Exception as e:
            logging.error("关闭窗口出错 {0}".format(e), exc_info=True)


    def GetHostInformation(self):
        HostInformation={}
        try:
            IPv4Abbress=''
            MAC=''
            wmi_Win32_OperatingSystem = self.wmiobj.Win32_OperatingSystem()[0]  # 获取计算机运行环境信息
            wmi_Win32_ComputerSystem = self.wmiobj.Win32_ComputerSystem()[0]    # 获取计算机CPU数量,内存大小,主板相关信息
            wmi_Win32_Processor = self.wmiobj.Win32_Processor()[0]              #用于获取CPU详细信息
            NetworkAdapterConfiguration  = self.wmiobj.Win32_NetworkAdapterConfiguration (IPEnabled=1)
            wmi_Win32_Board=self.wmiobj.Win32_BaseBoard()
            HostNode=platform.node()    #计算机网络名称
            HostInformation['hostName']=HostNode
            #获取本机电脑名
            Node= socket.getfqdn(socket.gethostname(  ))
            #获取本机ip
            IPv4Abbress = socket.gethostbyname(Node)
            HostInformation['hostIpv4']=IPv4Abbress
            HostName = wmi_Win32_OperatingSystem.Caption                    # 获取系统版本
            HostInformation['hostOs']=HostName
            for iteam in NetworkAdapterConfiguration:
                if IPv4Abbress in iteam.IPAddress:
                    MAC=iteam.MacAddress
            HostInformation['hostMac']=MAC
            HostOSArchitecture =wmi_Win32_OperatingSystem.OSArchitecture #获取操作系统类型(32bit/64bit)
            HostInformation['hostOsBit']=HostOSArchitecture
            HostLanguages =wmi_Win32_OperatingSystem.MUILanguages[0] #获取操作系统语言版本
            HostInformation['hostOsLanguage']=HostLanguages
            HostSerialNumber =wmi_Win32_OperatingSystem.SerialNumber #获取操作系统序列号
            HostInformation['hostOsCode']=HostSerialNumber
            HostCPUNum = wmi_Win32_ComputerSystem.NumberOfProcessors
            HostInformation['hostCpuNum']=HostCPUNum
            HostCPUType = wmi_Win32_Processor.Name           #获取cpu类型
            HostInformation['hostCpuType']=HostCPUType
            HostManufacturer = wmi_Win32_ComputerSystem.Manufacturer      #获取主板厂商信息
            HostInformation['hostMainboardInc']=HostManufacturer
            HostBoardSerialNumber = wmi_Win32_Board[0].SerialNumber
            HostInformation['hostMainboardId']=HostBoardSerialNumber
            HostBoardModel = wmi_Win32_ComputerSystem.Model           #获取主板型号
            HostInformation['hostMainboardType']=HostBoardModel
            HostBoardSystemtype = wmi_Win32_ComputerSystem.SystemType       #获取主板架构类型
            HostInformation['hostMainboardStructure']=HostBoardSystemtype
            HostPhysicalMemory = int(wmi_Win32_ComputerSystem.TotalPhysicalMemory) / 1024 / 1024 #获取内存容量
            HostInformation['hostMemorySize']=HostPhysicalMemory
            HostClockSpeed = wmi_Win32_Processor.MaxClockSpeed #获取操作系统主频
            HostInformation['hostCpuFrequency']=HostClockSpeed
            HostL2CacheSize  = wmi_Win32_Processor.L2CacheSize #获取cpu二级缓存大小
            HostInformation['hostCpuCache']=HostL2CacheSize
            HostNumberOfCores =  wmi_Win32_Processor.NumberOfCores #获取核心数量
            HostInformation['hostCpuCore']=HostNumberOfCores
            HostDataWidth = wmi_Win32_Processor.DataWidth #获取计算机的CPU数据宽度
            HostInformation['hostCpuWidth']=HostDataWidth
        except Exception as e:
            logging.error("读取主机信息出错 {0}".format(e), exc_info=True)
        finally:
            return HostInformation

    def SubmitInfromation(self,HostInformation,CurrentWindow):
        CheckResult=self.CheckInformation(HostInformation)   #获取设备注册所需信息
        try:
            if CheckResult==1:
                tk.messagebox.showinfo(title='提示',message='设备注册信息已传输。')
                try:
                    self.Communcate.DeviceRegist(HostInformation)
                except Exception as e:
                    logging.error("传输设备信息出错 {0}".format(e), exc_info=True)
                self.Close(CurrentWindow)        #关闭界面
            elif CheckResult==0:
                tk.messagebox.showinfo(title='提示',message='设备注册信息出错，请重新获取。')      #注册信息不符合要求，不进行传输
            else:
                tk.messagebox.showinfo(title='提示',message='信息检查出错。')
                print("信息检查出错。")
        except Exception as e:
            logging.error("传输设备信息出错 {0}".format(e), exc_info=True)


    def CheckInformation(self,HostInformation):         #检测信息是否合格
        try:
            for iteam in HostInformation.keys():
                if HostInformation[iteam]=='' or HostInformation[iteam]==None:
                    return 0
                if len(HostInformation)!=18:
                    return 0
            try:
                pattern=re.compile('(\d+)')
                HostInformation['hostOsBit']=int(re.findall(pattern,HostInformation['hostOsBit'])[0])
            except Exception as e:
                logging.error("未找到操作系统位数 {0}".format(e), exc_info=True)
                return 0
        except Exception as e:
            logging.error("传输设备信息不符合要求 {0}".format(e), exc_info=True)
            return 0
        else:
            return 1

    def ReGet(self):          #重新获取设备注册信息
        self.HostInformation=self.GetHostInformation()
        try:

            try:
                self.NodeText.configure(state=tk.NORMAL)
                self.NodeText.delete('1.0',END)
                self.NodeText.insert(tk.END,self.HostInformation['hostName'])
                self.NodeText.configure(state=tk.DISABLED)
            except Exception:
                pass

            try:
                self.IPv4Text.configure(state=tk.NORMAL)
                self.IPv4Text.delete('1.0',END)
                self.IPv4Text.insert(tk.END,self.HostInformation['hostIpv4'])
                self.IPv4Text.configure(state=tk.DISABLED)
            except Exception:
                pass

            try:
                self.OsVersionText.configure(state=tk.NORMAL)
                self.OsVersionText.delete('1.0',END)
                self.OsVersionText.insert(tk.END,self.HostInformation['hostOs'])
                self.OsVersionText.configure(state=tk.DISABLED)
            except Exception:
                pass

            try:
                self.MACText.configure(state=tk.NORMAL)
                self.MACText.delete('1.0',END)
                self.MACText.insert(tk.END,self.HostInformation['hostMac'])
                self.MACText.configure(state=tk.DISABLED)
            except Exception:
                pass

            try:
                self.OsBitText.configure(state=tk.NORMAL)
                self.OsBitText.delete('1.0',END)
                self.OsBitText.insert(tk.END,self.HostInformation['hostOsBit'])
                self.OsBitText.configure(state=tk.DISABLED)
            except Exception:
                pass

            try:
                self.OsLanguageText.configure(state=tk.NORMAL)
                self.OsLanguageText.delete('1.0',END)
                self.OsLanguageText.insert(tk.END,self.HostInformation['hostOsLanguage'])
                self.OsLanguageText.configure(state=tk.DISABLED)
            except Exception:
                pass

            try:
                self.OsCodeText.configure(state=tk.NORMAL)
                self.OsCodeText.delete('1.0',END)
                self.OsCodeText.insert(tk.END,self.HostInformation['hostOsCode'])
                self.OsCodeText.configure(state=tk.DISABLED)
            except Exception:
                pass

            try:
                self.CpuNumText.configure(state=tk.NORMAL)
                self.CpuNumText.delete('1.0',END)
                self.CpuNumText.insert(tk.END,self.HostInformation['hostCpuNum'])
                self.CpuNumText.configure(state=tk.DISABLED)
            except Exception:
                pass

            try:
                self.CpuTypeText.configure(state=tk.NORMAL)
                self.CpuTypeText.delete('1.0',END)
                self.CpuTypeText.insert(tk.END,self.HostInformation['hostCpuType'])
                self.CpuTypeText.configure(state=tk.DISABLED)
            except Exception:
                pass

            try:
                self.MainboardIncText.configure(state=tk.NORMAL)
                self.MainboardIncText.delete('1.0',END)
                self.MainboardIncText.insert(tk.END,self.HostInformation['hostMainboardInc'])
                self.MainboardIncText.configure(state=tk.DISABLED)
            except Exception:
                pass

            try:
                self.MainboardIdText.configure(state=tk.NORMAL)
                self.MainboardIdText.delete('1.0',END)
                self.MainboardIdText.insert(tk.END,self.HostInformation['hostMainboardId'])
                self.MainboardIdText.configure(state=tk.DISABLED)
            except Exception:
                pass

            try:
                self.MainboardTypeText.configure(state=tk.NORMAL)
                self.MainboardTypeText.delete('1.0',END)
                self.MainboardTypeText.insert(tk.END,self.HostInformation['hostMainboardType'])
                self.MainboardTypeText.configure(state=tk.DISABLED)
            except Exception:
                pass

            try:
                self.MainboardStructureText.configure(state=tk.NORMAL)
                self.MainboardStructureText.delete('1.0',END)
                self.MainboardStructureText.insert(tk.END,self.HostInformation['hostMainboardStructure'])
                self.MainboardStructureText.configure(state=tk.DISABLED)
            except Exception:
                pass

            try:
                self.MemorySizeText.configure(state=tk.NORMAL)
                self.MemorySizeText.delete('1.0',END)
                self.MemorySizeText.insert(tk.END,self.HostInformation['hostMemorySize'])
                self.MemorySizeText.configure(state=tk.DISABLED)
            except Exception:
                pass

            try:
                self.CpuFrequencyText.configure(state=tk.NORMAL)
                self.CpuFrequencyText.delete('1.0',END)
                self.CpuFrequencyText.insert(tk.END,self.HostInformation['hostCpuFrequency'])
                self.CpuFrequencyText.configure(state=tk.DISABLED)
            except Exception:
                pass

            try:
                self.CpuCacheText.configure(state=tk.NORMAL)
                self.CpuCacheText.delete('1.0',END)
                self.CpuCacheText.insert(tk.END,self.HostInformation['hostCpuCache'])
                self.CpuCacheText.configure(state=tk.DISABLED)
            except Exception:
                pass

            try:
                self.CpuCoreText.configure(state=tk.NORMAL)
                self.CpuCoreText.delete('1.0',END)
                self.CpuCoreText.insert(tk.END,self.HostInformation['hostCpuCore'])
                self.CpuCoreText.configure(state=tk.DISABLED)
            except Exception:
                pass

            try:
                self.CpuWidthText.configure(state=tk.NORMAL)
                self.CpuWidthText.delete('1.0',END)
                self.CpuWidthText.insert(tk.END,self.HostInformation['hostCpuWidth'])
                self.CpuWidthText.configure(state=tk.DISABLED)
            except Exception:
                pass
        except Exception as e:
            logging.error("重新获取设备信息显示失败 {0}".format(e), exc_info=True)


    def StartDeviceRegistUI(self):
        try:
            DeviceRegistUI=tk.Tk()        #创建界面

            DeviceRegistUI.geometry('800x700')
            DeviceRegistUI.title("设备注册")

            LabelTitle=tk.Label(DeviceRegistUI,text='欢迎使用基线检查平台',font=("楷体",20,"bold"),width=20,height=1)
            LabelTitle.place(x=400,y=10,anchor='n')

            self.HostInformation=self.GetHostInformation()

            LabelNode=tk.Label(DeviceRegistUI,text='设备名称：',font=("楷体",15))
            LabelNode.place(x=200,y=80,anchor='e')

            self.NodeText=tk.Text(DeviceRegistUI,width=75,height=1,state=tk.DISABLED)
            self.NodeText.place(x=500,y=80,anchor='center')        #创建文本框，并将相应的内容填入其中

            try:
                self.NodeText.configure(state=tk.NORMAL)
                self.NodeText.insert(tk.END,self.HostInformation['hostName'])
                self.NodeText.configure(state=tk.DISABLED)
            except Exception:
                pass

            LabelIPv4=tk.Label(DeviceRegistUI,text='IPv4地址：',font=("楷体",15))
            LabelIPv4.place(x=200,y=110,anchor='e')

            self.IPv4Text=tk.Text(DeviceRegistUI,width=75,height=1,state=tk.DISABLED)
            self.IPv4Text.place(x=500,y=110,anchor='center')        #创建文本框，并将相应的内容填入其中

            try:
                self.IPv4Text.configure(state=tk.NORMAL)
                self.IPv4Text.insert(tk.END,self.HostInformation['hostIpv4'])
                self.IPv4Text.configure(state=tk.DISABLED)
            except Exception:
                pass

            LabelOSVersion=tk.Label(DeviceRegistUI,text='操作系统版本：',font=("楷体",15))
            LabelOSVersion.place(x=200,y=140,anchor='e')

            self.OsVersionText=tk.Text(DeviceRegistUI,width=75,height=1,state=tk.DISABLED)
            self.OsVersionText.place(x=500,y=140,anchor='center')        #创建文本框，并将相应的内容填入其中

            try:
                self.OsVersionText.configure(state=tk.NORMAL)
                self.OsVersionText.insert(tk.END,self.HostInformation['hostOs'])
                self.OsVersionText.configure(state=tk.DISABLED)
            except Exception:
                pass

            LabelMAC=tk.Label(DeviceRegistUI,text='MAC地址：',font=("楷体",15))
            LabelMAC.place(x=200,y=170,anchor='e')

            self.MACText=tk.Text(DeviceRegistUI,width=75,height=1,state=tk.DISABLED)
            self.MACText.place(x=500,y=170,anchor='center')        #创建文本框，并将相应的内容填入其中

            try:
                self.MACText.configure(state=tk.NORMAL)
                self.MACText.insert(tk.END,self.HostInformation['hostMac'])
                self.MACText.configure(state=tk.DISABLED)
            except Exception:
                pass

            LabelOsBit=tk.Label(DeviceRegistUI,text='操作系统位数：',font=("楷体",15))
            LabelOsBit.place(x=200,y=200,anchor='e')

            self.OsBitText=tk.Text(DeviceRegistUI,width=75,height=1,state=tk.DISABLED)
            self.OsBitText.place(x=500,y=200,anchor='center')        #创建文本框，并将相应的内容填入其中

            try:
                self.OsBitText.configure(state=tk.NORMAL)
                self.OsBitText.insert(tk.END,self.HostInformation['hostOsBit'])
                self.OsBitText.configure(state=tk.DISABLED)
            except Exception:
                pass

            LabelOsLanguage=tk.Label(DeviceRegistUI,text='操作系统语言：',font=("楷体",15))
            LabelOsLanguage.place(x=200,y=230,anchor='e')

            self.OsLanguageText=tk.Text(DeviceRegistUI,width=75,height=1,state=tk.DISABLED)
            self.OsLanguageText.place(x=500,y=230,anchor='center')        #创建文本框，并将相应的内容填入其中

            try:
                self.OsLanguageText.configure(state=tk.NORMAL)
                self.OsLanguageText.insert(tk.END,self.HostInformation['hostOsLanguage'])
                self.OsLanguageText.configure(state=tk.DISABLED)
            except Exception:
                pass

            LabelOsCode=tk.Label(DeviceRegistUI,text='操作系统语言：',font=("楷体",15))
            LabelOsCode.place(x=200,y=260,anchor='e')

            self.OsCodeText=tk.Text(DeviceRegistUI,width=75,height=1,state=tk.DISABLED)
            self.OsCodeText.place(x=500,y=260,anchor='center')        #创建文本框，并将相应的内容填入其中

            try:
                self.OsCodeText.configure(state=tk.NORMAL)
                self.OsCodeText.insert(tk.END,self.HostInformation['hostOsCode'])
                self.OsCodeText.configure(state=tk.DISABLED)
            except Exception:
                pass

            LabelCpuNum=tk.Label(DeviceRegistUI,text='CPU数量：',font=("楷体",15))
            LabelCpuNum.place(x=200,y=290,anchor='e')

            self.CpuNumText=tk.Text(DeviceRegistUI,width=75,height=1,state=tk.DISABLED)
            self.CpuNumText.place(x=500,y=290,anchor='center')        #创建文本框，并将相应的内容填入其中

            try:
                self.CpuNumText.configure(state=tk.NORMAL)
                self.CpuNumText.insert(tk.END,self.HostInformation['hostCpuNum'])
                self.CpuNumText.configure(state=tk.DISABLED)
            except Exception:
                pass

            LabelCpuType=tk.Label(DeviceRegistUI,text='CPU类型：',font=("楷体",15))
            LabelCpuType.place(x=200,y=320,anchor='e')

            self.CpuTypeText=tk.Text(DeviceRegistUI,width=75,height=1,state=tk.DISABLED)
            self.CpuTypeText.place(x=500,y=320,anchor='center')        #创建文本框，并将相应的内容填入其中

            try:
                self.CpuTypeText.configure(state=tk.NORMAL)
                self.CpuTypeText.insert(tk.END,self.HostInformation['hostCpuType'])
                self.CpuTypeText.configure(state=tk.DISABLED)
            except Exception:
                pass

            LabelMainboardInc=tk.Label(DeviceRegistUI,text='主板厂商：',font=("楷体",15))
            LabelMainboardInc.place(x=200,y=350,anchor='e')

            self.MainboardIncText=tk.Text(DeviceRegistUI,width=75,height=1,state=tk.DISABLED)
            self.MainboardIncText.place(x=500,y=350,anchor='center')        #创建文本框，并将相应的内容填入其中

            try:
                self.MainboardIncText.configure(state=tk.NORMAL)
                self.MainboardIncText.insert(tk.END,self.HostInformation['hostMainboardInc'])
                self.MainboardIncText.configure(state=tk.DISABLED)
            except Exception:
                pass

            LabelMainboardId=tk.Label(DeviceRegistUI,text='主板序列号：',font=("楷体",15))
            LabelMainboardId.place(x=200,y=380,anchor='e')

            self.MainboardIdText=tk.Text(DeviceRegistUI,width=75,height=1,state=tk.DISABLED)
            self.MainboardIdText.place(x=500,y=380,anchor='center')        #创建文本框，并将相应的内容填入其中

            try:
                self.MainboardIdText.configure(state=tk.NORMAL)
                self.MainboardIdText.insert(tk.END,self.HostInformation['hostMainboardId'])
                self.MainboardIdText.configure(state=tk.DISABLED)
            except Exception:
                pass

            LabelMainboardType=tk.Label(DeviceRegistUI,text='主板类型：',font=("楷体",15))
            LabelMainboardType.place(x=200,y=410,anchor='e')

            self.MainboardTypeText=tk.Text(DeviceRegistUI,width=75,height=1,state=tk.DISABLED)
            self.MainboardTypeText.place(x=500,y=410,anchor='center')        #创建文本框，并将相应的内容填入其中

            try:
                self.MainboardTypeText.configure(state=tk.NORMAL)
                self.MainboardTypeText.insert(tk.END,self.HostInformation['hostMainboardType'])
                self.MainboardTypeText.configure(state=tk.DISABLED)
            except Exception:
                pass

            LabelMainboardStructure=tk.Label(DeviceRegistUI,text='主板架构：',font=("楷体",15))
            LabelMainboardStructure.place(x=200,y=440,anchor='e')

            self.MainboardStructureText=tk.Text(DeviceRegistUI,width=75,height=1,state=tk.DISABLED)
            self.MainboardStructureText.place(x=500,y=440,anchor='center')        #创建文本框，并将相应的内容填入其中

            try:
                self.MainboardStructureText.configure(state=tk.NORMAL)
                self.MainboardStructureText.insert(tk.END,self.HostInformation['hostMainboardStructure'])
                self.MainboardStructureText.configure(state=tk.DISABLED)
            except Exception:
                pass

            LabelMemorySize=tk.Label(DeviceRegistUI,text='内存容量：',font=("楷体",15))
            LabelMemorySize.place(x=200,y=470,anchor='e')

            self.MemorySizeText=tk.Text(DeviceRegistUI,width=75,height=1,state=tk.DISABLED)
            self.MemorySizeText.place(x=500,y=470,anchor='center')        #创建文本框，并将相应的内容填入其中

            try:
                self.MemorySizeText.configure(state=tk.NORMAL)
                self.MemorySizeText.insert(tk.END,self.HostInformation['hostMemorySize'])
                self.MemorySizeText.configure(state=tk.DISABLED)
            except Exception:
                pass

            LabelCpuFrequency=tk.Label(DeviceRegistUI,text='CPU频率：',font=("楷体",15))
            LabelCpuFrequency.place(x=200,y=500,anchor='e')

            self.CpuFrequencyText=tk.Text(DeviceRegistUI,width=75,height=1,state=tk.DISABLED)
            self.CpuFrequencyText.place(x=500,y=500,anchor='center')        #创建文本框，并将相应的内容填入其中

            try:
                self.CpuFrequencyText.configure(state=tk.NORMAL)
                self.CpuFrequencyText.insert(tk.END,self.HostInformation['hostCpuFrequency'])
                self.CpuFrequencyText.configure(state=tk.DISABLED)
            except Exception:
                pass

            LabelCpuCache=tk.Label(DeviceRegistUI,text='CPU L2缓存：',font=("楷体",15))
            LabelCpuCache.place(x=200,y=530,anchor='e')

            self.CpuCacheText=tk.Text(DeviceRegistUI,width=75,height=1,state=tk.DISABLED)
            self.CpuCacheText.place(x=500,y=530,anchor='center')        #创建文本框，并将相应的内容填入其中

            try:
                self.CpuCacheText.configure(state=tk.NORMAL)
                self.CpuCacheText.insert(tk.END,self.HostInformation['hostCpuCache'])
                self.CpuCacheText.configure(state=tk.DISABLED)
            except Exception:
                pass

            LabelCpuCore=tk.Label(DeviceRegistUI,text='CPU核心数：',font=("楷体",15))
            LabelCpuCore.place(x=200,y=560,anchor='e')

            self.CpuCoreText=tk.Text(DeviceRegistUI,width=75,height=1,state=tk.DISABLED)
            self.CpuCoreText.place(x=500,y=560,anchor='center')        #创建文本框，并将相应的内容填入其中

            try:
                self.CpuCoreText.configure(state=tk.NORMAL)
                self.CpuCoreText.insert(tk.END,self.HostInformation['hostCpuCore'])
                self.CpuCoreText.configure(state=tk.DISABLED)
            except Exception:
                pass

            LabelCpuWidth=tk.Label(DeviceRegistUI,text='CPU数据宽度：',font=("楷体",15))
            LabelCpuWidth.place(x=200,y=590,anchor='e')

            self.CpuWidthText=tk.Text(DeviceRegistUI,width=75,height=1,state=tk.DISABLED)
            self.CpuWidthText.place(x=500,y=590,anchor='center')        #创建文本框，并将相应的内容填入其中

            try:
                self.CpuWidthText.configure(state=tk.NORMAL)
                self.CpuWidthText.insert(tk.END,self.HostInformation['hostCpuWidth'])
                self.CpuWidthText.configure(state=tk.DISABLED)
            except Exception:
                pass


            ReGet=tk.Button(DeviceRegistUI,text='重新获取信息',command=lambda:self.ReGet())
            ReGet.place(x=300,y=650,anchor='n')         #重新获取信息按钮

            Submit=tk.Button(DeviceRegistUI,text='提交注册信息',command=lambda:self.SubmitInfromation(self.HostInformation,DeviceRegistUI))
            Submit.place(x=500,y=650,anchor='n')       #提交信息按钮

            DeviceRegistUI.mainloop()
        except Exception as e:
            logging.error("设备注册界面创建失败 {0}".format(e), exc_info=True)


if __name__ == "__main__":
    login=LoginStart()
    login.start()    #执行该文件时调用生成登录界面
    #g=DeviceRegistUI()
    #g.Start()